var BASE = {}; //全局公用基础方法
BASE = (function () {
    var baseUrlLocal="https://api.bcdaren.com";
    var baseUrl="https://www.bcdaren.com";
    var baseImgURL = 'https://res.bcdaren.com';
    if(isLocal()){
        // baseUrlLocal="http://api.dev.bcdaren.com";
        // baseImgURL = 'http://res.dev.bcdaren.com';
        // baseUrl ="http://web.dev.bcdaren.com";
        baseUrlLocal = 'http://api.im.heiwuxs.cn';
        // baseUrlLocal = 'http://192.168.1.17:8080';
        baseImgURL = 'http://res.im.heiwuxs.cn';
        baseUrl = 'http://web.im.heiwuxs.cn';
    }
    /*是否是本地环境*/
    function isLocal() {
        var href = window.location.href;
        return  href.indexOf('localhost') > -1
                || href.indexOf('127.0.0.1') > -1
                || href.indexOf('bcdaren.com') < 0;
    }
    /**********************************公用方法start*********************************/
    /*请求接口的提示弹出层*/
    function loadingTips(flag,text,type) {
        var $loadingTips = $("#loadingTips");
        if(type == 'wrong'){
            $loadingTips.addClass('wrong');
        }else {
            $loadingTips.removeClass('wrong');
        }
        if ($loadingTips.length > 0) {
            $loadingTips.html("<p>" + text + "</p>");
        } else {
            var str = '<div id="loadingTips"><p>' + text + '</p></div>';
            $("body").append(str);
        }
        flag ? $loadingTips.show() : $loadingTips.hide();
    }
    /*自动消失的弹出提示框*/
    function clearpop(txt,time){
        if(!time){time=3000;}
        if($("#clearpop").length>0){
            $("#clearpop").html("<p>"+txt+"</p>").show();
        }else{
            var str='<div id="clearpop"><p>'+txt+'</p></div>';
            $("body").append(str);
        }
        setTimeout(function(){$("#clearpop").fadeOut(500);},time);
    }
    /*验证手机号码*/
    function verifyTel(inputtel){
        var tel = inputtel.trim();
        var reg=/^1(3|4|5|6|7|8|9)\d{9}$/;
        if(!tel){
            clearpop("请填写手机号！");
            return false;
        }
        if(!reg.test(tel)){
            clearpop("请填写正确的手机号");
            return false;
        }
        return true;
    }
    /*验证密码*/
    function verifyPas(inputpas){
        var pas = inputpas.trim();
        var reg=/^[a-zA-Z0-9]{6,12}$/;
        if(!pas){
            clearpop("请填写密码！");
            return false;
        }
        if(!reg.test(pas)){
            clearpop("密码为6-12位字母加数字的组合");
            return false;
        }
        return true;
    }
    /*倒计时更多选项*/
    function mortime(obj){
        var i=120;
        $(obj).attr("disabled",true);
        var timer= setInterval(downtime,1000);
        function downtime(){
            i--;
            $(obj).val('重发('+i+')').text('重发('+i+')');
            if(i<=0){
                $(obj).attr("disabled",false);
                $(obj).val('重新发送').text('重新发送');
                timer=clearInterval(timer)
            }
        }
    }
    /*设置本地缓存*/
    function setStore(name,content) {
        var _content = content;
        if (!name) return;
        if (localStorage[name] && window.location.href.includes('http://localhost')) {
            console.log('已存在该本地存储键值');
        }
        if (typeof content !== 'string') {
            _content = JSON.stringify(_content);
        }
        localStorage.setItem(name, _content);
    }
    /*获取本地缓存*/
    function getStore (name){
        if (!name) return '';
        var result= localStorage.getItem(name);
        if(name=='userInfo'){ //用户信息单独处理
            return JSON.parse(result);
        }
        return result;
    }
    /*清除本地缓存*/
    function  removeStore(name){
        if (!name) return;
        localStorage.removeItem(name);
    }
    /*删除cookie*/
    function _delCookie(name){
        setCookie(name, '', -1);
    }
    /*清除所有的缓存*/
    function clearAll(){
        var cookie = document.cookie;
        BASE.removeStore('chekInDate');
        BASE.removeStore('qqlist');
        BASE.removeStore('userToken');
        BASE.removeStore('userInfo');
        BASE.setCookie('SESSION', null,-1);
        sessionStorage.clear();
        if(!cookie){
            return;
        }
        var arr = cookie.split(';');
        arr.forEach(function (v) {
            var name = v.split('=')[0];
            _delCookie(name);
        });
        BASE.COMMON.userInfoFill();
    }
    /*设置cookie*/
    function setCookie(name,value,day) {
        var date = new Date();
        date.setDate(date.getDate() + Math.ceil(day/1));
        document.cookie = name+"="+value+';path=/;domain=bcdaren.com;expires='+date;
    }
    /*获取请求参数*/
    function getUrlParam(name) {
        //构造一个含有目标参数的正则表达式对象
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        //匹配目标参数
        var r = window.location.search.substr(1).match(reg);
        //返回参数值
        if (r != null) return r[2];
        return null;
    }
        /**********************************ajax start*********************************/
    /*公用请求方法处理*/
    function _commonajax(type, url, sendData, callback) {
        $.ajax({
            type:type,
            url:url,
            timeout: 5000,
            data:sendData,
            xhrFields: {
                withCredentials: true
            },
            beforeSend : function(request) {
                var token = getStore('userToken');
                if (token) {
                    request.setRequestHeader("token", token);
                }
                var login =  BASE.getStore('saveLoginIs');
                if (login) {
                    request.setRequestHeader("saveLoginIs", login);
                }
            },
            crossDomain: true,
            success:function (res) {
                if(callback&&typeof callback=="function"){
                    callback(res);
                }
            },
            error:function (err) {
                console.log(err);
            }
        });
    }
    /*公用请求方法处理*/
    function _ajax(type, url, sendData, callback) {
        $.ajax({
            type:type,
            url:url,
            timeout: 5000,
            data:sendData,
            xhrFields: {
                withCredentials: true
            },
            beforeSend : function(request) {
                var token = getStore('userToken');
                var login =  BASE.getStore('saveLoginIs');
                if (token) {
                    request.setRequestHeader("token", token);
                }
                if (login) {
                    request.setRequestHeader("saveLoginIs", login);
                }
            },
            crossDomain: true,
            success:function (res) {
                if(res.ecode == "SESSION_INVALID_EXCEPTION") { //登录过期
                    clearAll();
                    window.location.href = '/login.html';
                    return;
                }
                if(callback&&typeof callback=="function"){
                    callback(res);
                }
            },
            error:function (err) {
                console.log(err);
            }
        });
    }
    /*公用请求方法处理返回code为200的数*/
    function _apiajax(type, url, sendData, callback) {
        $.ajax({
            type:type,
            url:url,
            data:sendData,
            timeout: 5000,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            beforeSend : function(request) {
             var token = getStore('userToken');
                if (token) {
                    request.setRequestHeader("token", token);
                }
                var login =  BASE.getStore('saveLoginIs');
                if (login) {
                    request.setRequestHeader("saveLoginIs", login);
                }
             },
            success:function (res) {
                if(res.ecode == "SESSION_INVALID_EXCEPTION") { //登录过期
                    clearAll();
                    window.location.href = '/login.html';
                    return;
                }
                if(res.code!=200){
                    clearpop(res.message);
                    return;
                }
                if(callback&&typeof callback=="function"){
                    callback(res.data);
                }
            },
            error:function (err) {
                console.log(err);
            }
        });
    }
    /*公用请求参数处理*/
    function _ajaxDataSet(type, arguments,callabck) {
        var arg = arguments;
        var url = arg[0];
        var sendData = null;
        var fn = null;
        if (arg.length==2){
            if(typeof arg[1] == 'function'){
                fn = arg[1];
            }else {
                sendData = arg[1];
            }
        }
        if (arg.length==3){
            sendData = arg[1];
            fn = arg[2];
        }
        if (url.indexOf('http://') < 0 ||url.indexOf('https://') < 0){
            var href = window.location.href;
            url = baseUrlLocal + url;
            /*if(href.indexOf('localhost') > -1 || href.indexOf('127.0.0.1') > -1){
                url = baseUrlLocal + url;
            }else {
                url = baseUrlOnline + url;
            }*/
        }
        callabck(type, url, sendData, fn);
    }
    /*带请求头封装数据请求code为200的请求*/
    function apiPost() {
        _ajaxDataSet('post',arguments, _apiajax);
    }
    function apiGet() {
        _ajaxDataSet('get',arguments, _apiajax);
    }
    /*不带请求头封装数据不处理请求*/
    function postHttp() {
        _ajaxDataSet('post',arguments, _ajax);
    }
    function getHttp() {
        _ajaxDataSet('get',arguments, _ajax);
    }
    function postCommon() {
        _ajaxDataSet('post',arguments, _commonajax);
        
    }
    function getCommon() {
        _ajaxDataSet('get',arguments, _commonajax);

    }
    /************************************ajax end*********************************/
    
    /************************************事件start*********************************/
    /*回车键按下执行*/
    function keyEnter(callback) {
        var code = event.code;
        if(!code){
            return;
        }
        code = code.toString().toLowerCase();
        if (code == 'enter'){
            if(callback &&typeof callback == "function"){
                callback();
            }
        }
    }
    /************************************事件end********************************/
    return{
        baseUrlLocal:baseUrlLocal,
        baseImgURL:baseImgURL,
        baseUrl:baseUrl,
        isLocal:isLocal,
        getUrlParam:getUrlParam,
        loadingTips:loadingTips,
        clearpop:clearpop,
        verifyTel:verifyTel,
        verifyPas:verifyPas,
        mortime:mortime,
        setCookie:setCookie,
        setStore:setStore,
        getStore:getStore,
        removeStore:removeStore,
        clearAll:clearAll,
        apiPost:apiPost,
        apiGet:apiGet,
        postHttp:postHttp,
        getHttp:getHttp,
        keyEnter:keyEnter,
        postCommon:postCommon,
        getCommon:getCommon,
    };
    /**********************************公用方法end*********************************/
})();

